/* Copyright 2008 Milko Slavov
 * This file is part of GEH.
 * GEH is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * GEH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * See <http://www.gnu.org/licenses/>.
*/

package com.geh.event;

import java.util.ArrayList;

class ThreadPool {
	
	private static final long MAX_WAIT_FOR_STOP = 1000;
	private ArrayList <Worker> workers_;
	private SynchronizedQueue sQueue;
	private int maxThread_;
	private boolean isStopped = false;
	
	private ThreadPool(int maxThread, int queueSize) {
		workers_ = new ArrayList<Worker>(maxThread);
		maxThread_ = maxThread;
		sQueue = new SynchronizedQueue(queueSize);
		for (int i = 0; i < maxThread; i++) {
			workers_.add(new Worker());
			workers_.get(i).start();
		}
	}

	static ThreadPool newInstance(int maxThread, int queueSize) {
	   return new ThreadPool(maxThread, queueSize);
	}
	
	public void enqueueTask(Runnable task) {
		if (isStopped)
			throw new IllegalArgumentException("You can't use stopped pool!");
		try {
			sQueue.enqueue(task);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			return;
		}
	}
	
	public boolean isStopped() {
		return isStopped;
	}

	/**
     * Stops the pool after all tasks are executed.
     */

	public synchronized void stopPool() {
		synchronized(sQueue) {
			while (!sQueue.isEmpty()) {
				try {
					sQueue.wait(MAX_WAIT_FOR_STOP);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
			}
			isStopped = true;
			for (int i = maxThread_ - 1; i >= 0; i--)
				workers_.remove(i).interrupt();
		}
	}
	
	private class Worker extends Thread {
		
		public void run() {
			while(!interrupted()) {
				Runnable task = null;
				try {
					task = (Runnable) sQueue.dequeue();
					task.run();
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
				if (isInterrupted() && workers_.contains(this))
					interrupted();
			}
		}
		
	}
	
}
